using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_SpeakerItem : UIBaseNode
    {
        #region Template Generate,don't modify

        protected class UIB_UIN_SpeakerItem
        {
            #region ObjectBinding Generate

            public UnityEngine.Transform live2DParent { protected set; get; }
            public UnityEngine.GameObject live2D { protected set; get; }
            public IQIGame.Onigao.Framework.ExRawImage image { protected set; get; }
            public UnityEngine.GameObject spine { protected set; get; }
            public UnityEngine.RectTransform spineParent { protected set; get; }
            public UnityEngine.CanvasGroup uIN_SpeakerItem { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<UnityEngine.Transform>("live2DParent", out var __tbv0);
                this.live2DParent = __tbv0;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("live2D", out var __tbv1);
                this.live2D = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExRawImage>("image", out var __tbv2);
                this.image = __tbv2;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("spine", out var __tbv3);
                this.spine = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.RectTransform>("spineParent", out var __tbv4);
                this.spineParent = __tbv4;
                __binding.TryGetVariableValue<UnityEngine.CanvasGroup>("uIN_SpeakerItem", out var __tbv5);
                this.uIN_SpeakerItem = __tbv5;
            }

            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify

        #region fields

        private static readonly Color activeColor = Color.white;
        private static readonly Color deactiveColor = new Color(79f / 255f, 79f / 255f, 79f / 255f, 1f);

        private int _live2D;
        private int _spine;

        #endregion fields

        #region properties

        protected UIB_UIN_SpeakerItem ui { get; set; }
        protected UIMsgDispatcher uiMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_SpeakerItem();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this.isUpdate = true;
        }

        protected override void OnShow()
        {
        }

        protected override void OnHide()
        {
            if (this._live2D > 0)
            {
                Live2DManager.Instance.Remove(this._live2D);
                this._live2D = 0;
            }
            if (this._spine > 0)
            {
                SpineManager.Instance.Remove(this._spine);
                this._spine = 0;
            }
        }

        /// <summary>
        /// 添加UGUI侦听
        /// </summary>
        protected override void AddUGUIListener()
        {
        }

        /// <summary>
        /// 添加全局侦听（MsgDispatcher）
        /// </summary>
        protected override void AddMsgListeners()
        {
        }

        protected override void OnDispose()
        {
        }

        #region methonds

        public void Active()
        {
            if (this._live2D > 0)
            {
                Live2DManager.Instance.Get(this._live2D).render.ModelMultiplyColor = activeColor;
            }
            else if (this._spine > 0)
            {
                var rSpineEntity = SpineManager.Instance.GetEntity(this._spine);
                if (rSpineEntity.graphic)
                {
                    rSpineEntity.graphic.color = activeColor;
                }
            }
            else
            {
                this.ui.image.color = activeColor;
            }
        }

        public void DeActive()
        {
            if (this._live2D > 0)
            {
                Live2DManager.Instance.Get(this._live2D).render.ModelMultiplyColor = deactiveColor;
            }
            else if (this._spine > 0)
            {
                var rSpineEntity = SpineManager.Instance.GetEntity(this._spine);
                if (rSpineEntity.graphic)
                {
                    rSpineEntity.graphic.color = deactiveColor;
                }
            }
            else
            {
                this.ui.image.color = deactiveColor;
            }
        }

        public async UniTask Refresh(StorySpeakerConfig.EStorySpeakerType speakerType, int npcID, ExCanvas sortingCanvas)
        {
            this.ui.image.gameObject.SetActive(speakerType == StorySpeakerConfig.EStorySpeakerType.Image);
            this.ui.live2D.SetActive(speakerType == StorySpeakerConfig.EStorySpeakerType.Live2D);
            this.ui.spine.SetActive(speakerType == StorySpeakerConfig.EStorySpeakerType.Spine);

            if (npcID <= 0)
            {
                return;
            }
            var rNpc = TableCenter.storyNpc.Get(npcID);
            if (rNpc == null)
            {
                return;
            }
            if (this._live2D > 0)
            {
                Live2DManager.Instance.Remove(this._live2D);
                this._live2D = 0;
            }
            if (speakerType == StorySpeakerConfig.EStorySpeakerType.Image)
            {
#if UNITY_EDITOR
                if (StoryClientUtil.IsEditorMode)
                {
                    var rTex = AssetDatabase.LoadAssetAtPath<Texture>("Assets/" + rNpc.Image_fullPath);
                    this.ui.image.texture = rTex;
                }
                else
#endif
                {
                    this.SetRawImageTexture(this.ui.image, rNpc.Image_fullPath);
                }
            }
            else if (speakerType == StorySpeakerConfig.EStorySpeakerType.Live2D)
            {
                this._live2D = await Live2DManager.Instance.CreateAsync(rNpc.Live2D, this.ui.live2DParent, sortingCanvas.currCav.sortingLayerName, sortingCanvas.currCav.sortingOrder);
                var rLive2D = Live2DManager.Instance.Get(this._live2D);
                // live2D自带的LastMultiplyColor导致刚加载出来的资源会被强制使用默认颜色，等两帧再显示
                rLive2D.render.Opacity = 0;
                rLive2D.render.OnLateUpdate();
                rLive2D.render.OnLateUpdate();
                rLive2D.render.Opacity = 1;
            }
            else if (speakerType == StorySpeakerConfig.EStorySpeakerType.Spine)
            {
                this._spine = await SpineManager.Instance.GetSpine(this.ui.spineParent, rNpc.Spine);
            }
        }

        public float GetAlpha()
        {
            if (this._live2D > 0)
            {
                var rLive2D = Live2DManager.Instance.Get(this._live2D);
                return rLive2D?.render.Opacity ?? 1;
            }
            else
            {
                return this.ui.uIN_SpeakerItem.alpha;
            }
        }

        public void SetAlpha(float alpha)
        {
            if (this._live2D > 0)
            {
                var rLive2D = Live2DManager.Instance.Get(this._live2D);
                if (rLive2D != null)
                {
                    rLive2D.render.Opacity = alpha;
                }
            }
            else
            {
                this.ui.uIN_SpeakerItem.alpha = alpha;
            }
        }

        public void PlayAnimation(string animation, bool isLoop)
        {
            if (this._live2D > 0)
            {
                var rLive2D = Live2DManager.Instance.Get(this._live2D);
                rLive2D?.animator.CrossFade(animation, 0, 0);
            }
            else if (this._spine > 0)
            {
                SpineManager.Instance.PlayAnimation(this._spine, animation, isLoop);
            }
        }

        #endregion methonds
    }
}